package org.data;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Clean3 {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        //1 获取job对象
        Configuration conf = new Configuration();
        conf.set("mapred.textoutputformat.separator",",");
        conf.set("mapred.textoutputformat.ignoreseparator","true");
        Job job = Job.getInstance(conf);

        //2 关联Driver类
        job.setJarByClass(Clean3.class);

        //3 关联Mapper和Reducer类
        job.setMapperClass(Clean3Mapper.class);
        job.setReducerClass(Clean3Reducer.class);

        //4 设置Map的输入输出类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        //5	设置最终的输入输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        //6	设置输入输出路径
        FileInputFormat.setInputPaths(job,new Path("D:\\data\\Taxi_Trips.csv"));
        FileOutputFormat.setOutputPath(job,new Path("D:\\data\\out3"));

        //7 提交job
        boolean result = job.waitForCompletion(true);
        System.exit(result?0:1);
    }
}


class Clean3Mapper extends Mapper<Object, Text,Text,Text> {
    private Text outK=new Text();
    private Text outV=new Text();

    protected  void map(Object key,Text value,Context context) throws IOException,InterruptedException{

        String[] csvComments = value.toString().split(",");

        if(!csvComments[19].equals("") && !csvComments[22].equals("") && !csvComments[5].equals("0.0") && !csvComments[5].equals("0")){
            if(!csvComments[19].startsWith("-")){
                if(!csvComments[19].equals("Pickup Centroid Location")) {
                    outK.set(csvComments[19] + "," + csvComments[22]);
                    outV.set(csvComments[5]);
                    context.write(outK, outV);
                }
            }
        }
    }
}
class Clean3Reducer extends Reducer<Text,Text,Text,Text> {

    public void reduce(Text key,Iterable<Text> values,Context context) throws IOException,InterruptedException {

        Text a = new Text();
        for(Text value:values){
            a.set(value);
            context.write(key,a);
        }

    }
}
